package com.example.aimultimodel.tools;

import org.springframework.ai.tool.annotation.Tool;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

/**
 * @author 18747
 */
public class WebPageFetcherTool {

    // 定义HTTP客户端，设置超时时间
    private static final HttpClient httpClient = HttpClient.newBuilder()
            .connectTimeout(Duration.ofSeconds(10))
            .build();

    /**
     * 获取指定URL的网页内容
     * @param url 网页地址（例如：https://example.com）
     * @return 网页的HTML内容字符串，获取失败时返回错误信息
     */
    @Tool(description = "获取指定URL的网页内容并返回，参数为网页的完整URL地址")
    public String getHtmlContent(String url) {
        try {
            // 创建HTTP请求
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .timeout(Duration.ofSeconds(15))
                    .header("User-Agent", "Mozilla/5.0 (Spring AI Tool)")
                    .GET()
                    .build();

            // 发送请求并获取响应
            HttpResponse<String> response = httpClient.send(
                    request,
                    HttpResponse.BodyHandlers.ofString()
            );

            // 检查响应状态码
            if (response.statusCode() == 200) {
                return response.body();
            } else {
                return "获取网页内容失败，状态码：" + response.statusCode();
            }

        } catch (Exception e) {
            return "获取网页内容时发生错误：" + e.getMessage();
        }
    }
}
